<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * wish商品上传
 */
class Wishproduct extends CI_Controller
{

    function __construct()
    {
        parent::__construct();
        $this->load->model('Function_m', 'fun');
        $this->load->model('Wishproduct_m', 'wish');
		$this->pageSize =$this->config->item('pagenum');
    }

    public function index()
    {
        $this->tpl->display("wishproduct/welcome.tpl");
    }

    public function wishproductupload()
    {
        $this->displaytpl();
    }

    //显示模板
    public function displaytpl()
    {


        $this->tpl->assign("productlist", $this->wish->displaytpl());
        $this->tpl->display("wishproduct/application.tpl");
    }


    public function fgetcsv_reg(& $handle, $length = null, $d = ',', $e = '"')
    {
        $d = preg_quote($d);
        $e = preg_quote($e);
        $_line = "";
        $eof = false;
        while ($eof != true) {
            $_line .= (empty ($length) ? fgets($handle) : fgets($handle, $length));
            $itemcnt = preg_match_all('/' . $e . '/', $_line, $dummy);
            if ($itemcnt % 2 == 0)
                $eof = true;
        }
        $_csv_line = preg_replace('/(?: |[ ])?$/', $d, trim($_line));
        $_csv_pattern = '/(' . $e . '[^' . $e . ']*(?:' . $e . $e . '[^' . $e . ']*)*' . $e . '|[^' . $d . ']*)' . $d . '/';
        preg_match_all($_csv_pattern, $_csv_line, $_csv_matches);
        $_csv_data = $_csv_matches[1];
        for ($_csv_i = 0; $_csv_i < count($_csv_data); $_csv_i++) {
            $_csv_data[$_csv_i] = preg_replace('/^' . $e . '(.*)' . $e . '$/s', '$1', $_csv_data[$_csv_i]);
            $_csv_data[$_csv_i] = str_replace($e . $e, $e, $_csv_data[$_csv_i]);
        }
        return empty ($_line) ? false : $_csv_data;
    }

    //Wish退款信息
    public function wishrefund()
    {
        $nowpage = $_REQUEST["pageid"];
        if ($nowpage == "") $nowpage = 1;
        $action=$this->input->get("action");

        if ($this->input->get_post('shopid')) {
            $where .= " AND A.shopid = " . intval($this->input->get_post('shopid'));
            $this->tpl->assign("shopid", intval($this->input->get_post('shopid')));
        }

        if ($this->input->get_post('other')) {
            $other = trim($this->input->get_post('other'));
            if (strstr($other, ",")) {
                $others = explode(",", $other);
                $where .= " and (";
                foreach ($others as $key => $r) {
                    if ($key > 0) $k = "or";
                    $where .= " $k A.tradeid='" . $r . "'";
                }
                $where .= ")";

            } else {
                $where .= " and  (
					 A.tradeid =   '" . $other . "' or A.order_sn = '" . $other . "'
					) ";
            }
            $this->tpl->assign("other", trim($this->input->get_post('other')));
        }


        if ($this->input->get_post('ty')) {
            if ($this->input->get_post('ty') == 1) $tys = "ordertime";
            if ($this->input->get_post('ty') == 2) $tys = "Refund_Date";


            $this->tpl->assign("ty", trim($this->input->get_post('ty')));
        }
		

        $starttime = trim($this->input->get('starttime'));
        if ($starttime) {
           
                $times = $starttime . " 00:00:00";

            $where .= " AND ($tys >= '" . $times . "')";
            $this->tpl->assign("starttime", $starttime);
        }

        $endtime = trim($this->input->get('endtime'));
        if ($endtime) {
          
				$times = $endtime . " 23:59:59";

            $where .= " AND ($tys <= '" . $times . "')";
            $this->tpl->assign("endtime", $endtime);
        }
        if ($this->input->get('orderby')) {
            $orderbyst = $this->input->get('orderby');
            if ($orderbyst == 1) {
                $orderby = " order by A.orderTime ASC";
                $this->tpl->assign("orderbyst", 2);
            } else {
                $orderby = " order by A.orderTime DESC";
                $this->tpl->assign("orderbyst", 1);
            }
        } else {
            $orderby = " order by A.id DESC";
            $this->tpl->assign("orderby", 1);
        }
        if($action=='down_excel'){
            require dirname(__FILE__)."/../../fuman/ClassesExcel/PHPExcel.php";
            //.....此处略去从数据库获取数据的过程，$a为需要导出的数组......
            $numArr = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');
            // Create new PHPExcel object
            $objPHPExcel = new PHPExcel();
            //NO. 	商品编号 	名称 	总库存数 	总成本价值
            $arr = array('订单编号','店铺','退款金额(RMB)','退款金额(USD)','退款比例','退款时间','订单时间','退款原因','SKU');
            // 输出标题
            //echo date('H:i:s') , " Add some data" , EOL;
            //设置换行
            //$objPHPExcel->getActiveSheet()->getStyle('H')->getAlignment()->setWrapText(true);
            $objPHPExcel->getActiveSheet()->getStyle('Y')->getAlignment()->setWrapText(true);
            //设置相应列的宽度
            $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('A')->setWidth(25);
            $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('B')->setWidth(20);
            $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('C')->setWidth(15);
            $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('D')->setWidth(15);
            $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('E')->setWidth(12);
            $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('G')->setWidth(20);
            $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('H')->setWidth(26);
            $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('I')->setWidth(15);
            $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('F')->setWidth(18);
            //输出第一行
            $objPHPExcel->setActiveSheetIndex(0)
               ->setCellValue('A1', $arr[0])
             ->setCellValue('B1', $arr[1])
             ->setCellValue('C1', $arr[2])
             ->setCellValue('D1', $arr[3])
             ->setCellValue('E1', $arr[4])
             ->setCellValue('F1', $arr[5])
             ->setCellValue('G1', $arr[6])
             ->setCellValue('H1', $arr[7])
             ->setCellValue('I1', $arr[8])
             ->setCellValue('J1', $arr[9])
               ->setCellValue('K1', $arr[10])
               ->setCellValue('L1', $arr[11]);
             $order_list = $this->fun->getdatabaseslist("db_wish_refund A LEFT JOIN db_order_list B on A.order_id = B.order_id",
              $where, "A.*,B.ordertime", $orderby);
             //dump($order_list[1]);
            //输出内容
            foreach($order_list as $i=>$li){
              $a=$order_list;
              $objPHPExcel->getActiveSheet()->getStyle($numArr[0].($i+2))->getFont()->getColor()->setARGB("00".$td_color);
             $objPHPExcel->setActiveSheetIndex(0)
              ->setCellValueExplicit($numArr[0].($i+2), $li['tradeid'])
              ->setCellValueExplicit($numArr[1].($i+2), $li['shopname'])
              ->setCellValue($numArr[2].($i+2), $li['Refund_Amount_Rmb'])
              ->setCellValue($numArr[3].($i+2), $li['Refund_Amount'])
              ->setCellValue($numArr[4].($i+2), $li['Refund_Responsibility'])
              ->setCellValue($numArr[5].($i+2), $li['Refund_Date'])
              ->setCellValue($numArr[6].($i+2), $li['ordertime'])
              ->setCellValueExplicit($numArr[7].($i+2), $li['Refund_Reason'])
              ->setCellValue($numArr[8].($i+2), $li['goods_sn'])
              //->setCellValue($numArr[9].($i+2), $td_color)
              ->setCellValue($numArr[10].($i+2), '');
            }
            /*$max_line=count($order_list);
            $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue($numArr[0].($max_line+2), "合计：")
            ->setCellValue($numArr[2].($max_line+2), $totalinfo['total_quantity'])
              ->setCellValue($numArr[3].($max_line+2), $totalinfo['total_costprice']);
            */
            $site_root=$_SERVER['DOCUMENT_ROOT'];
              
            // Rename worksheet
            //echo date('H:i:s') , " Rename worksheet" , EOL;
            $dirName ="dhlexpress";//目录名
            $old_filename=$filename;
            //$filename = iconv("utf-8","gb2312//IGNORE",$filename);
            $fileName = "wish_refund_".date("Y-m-d");//文件名\uploads\DHL
            $objPHPExcel->getActiveSheet()->setTitle('Sheet1');
             
            // Set active sheet index to the first sheet, so Excel opens this as the first sheet
            $objPHPExcel->setActiveSheetIndex(0);
             
            // Save Excel 2007 file
            //echo date('H:i:s') , " Write to Excel2007 format" , EOL;
            $callStartTime = microtime(true);
    
            $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
            $objWriter->save($site_root.'/uploads/'.$dirName.'/'.$fileName.'.xlsx');
             
            header('Location:http://'.$_SERVER['HTTP_HOST'].'/uploads/'.$dirName.'/'.$fileName.'.xlsx');
        }else{
            $sql = "SELECT sum(A.Refund_Amount_Rmb) as total_refund_rmb,sum(A.Refund_Amount) as total_refund_usd FROM db_wish_refund A LEFT JOIN db_order_list B on A.order_id = B.order_id WHERE 1 ".$where;
            $rss = $this->db->query($sql)->row_array();
            $this->tpl->assign("total_refund_rmb",$rss['total_refund_rmb']);
            $this->tpl->assign("total_refund_usd",$rss['total_refund_usd']);

            $list = $this->fun->getalllist("db_wish_refund A LEFT JOIN db_order_list B on A.order_id = B.order_id", $where, $nowpage, $if_csv, $this->pageSize, $orderby, "A.*,B.ordertime");
            foreach ($list["list"] as $key => $rs) {
    			  $list["list"][$key]["Refund_Responsibility"] = intval($rs["Refund_Responsibility"]);//利润
            }
            $pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
            $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
            $this->tpl->assign("total", $list["total"]);
            $this->tpl->assign('query_string',$_SERVER['QUERY_STRING']);
            $this->tpl->assign("pageList", $pageList);
            $this->tpl->assign("d_shop", $this->fun->getdatabaseslist('d_shop', " AND openflag= 1 AND platfrom='16'", 'id,name', ' order by name asc'));            //查所有店铺
            $this->tpl->assign("orderlist", $list["list"]);
            $this->tpl->assign('st', date("Y-m-d"));
            $current = $this->input->get('current') ? $this->input->get('current') : 0;
            $this->tpl->assign('current', $current);
            $this->tpl->display("wishproduct/wishrefund.tpl");
        }
    }


    public function ajaxbutton()
    {
        $op = $this->input->get_post('op');
        if ($op == 'search') {
            $osn = trim($this->input->get('kw'));

            $this->tpl->assign("productlist", $this->wish->displaytpl('0', $osn));
            $this->tpl->assign("kw", $osn);
            $this->tpl->display("wishproduct/application.tpl");
        }

        if ($op == 'statussearch') {
            $osn = trim($this->input->get('kw'));

            $this->tpl->assign("statuslist", $this->wish->status($osn));
            $this->tpl->assign("kw", $osn);
            $this->tpl->display("wishproduct/status.tpl");
        }

        if ($op == 'savebatchexcel') {
            //setlocale(LC_ALL, 'zh_CN.UTF-8');
            $filename = $_FILES['upfile']['tmp_name'];
            $handle = fopen($filename, 'r');
            $upload = array();
            while ($data = fgetcsv($handle)) {
                unset($info);
                $info = array();
                foreach ($data as $v) {
                    $info[] = htmlentities($v);
                }
                $upload[] = $info;

            }
            //setlocale(LC_ALL,NULL);
            // var_dump($upload);
            // exit;
            $uploadjson = json_encode($upload);

            $this->wish->upload($uploadjson);
            $url = "/wishproduct/wishproductupload?rand=" . mt_rand(0, 1000);
            header("Location: {$url}");

        }

        if ($op == 'setshop') {
            //查询店铺，返回店铺名称和id号
            $str = $this->wish->selectshop();
            return $str;
        }

        if ($op == 'saveupload') {
            $productid = $this->input->post('productid');
            $shopid = $this->input->post('shopid');
            $this->wish->saveupload($productid, $shopid);
            echo "/wishproduct/wishproductupload?rand=" . mt_rand(0, 1000);;
        }
        //执行上传程序
        if ($op == "upload") {
            $this->load->library('Wishuploadproduct');
            $this->wishuploadproduct->upload();
        }

        if ($op == "creatproduct") {
            $type = $this->input->get('type');
            //意味着是创建新的产品
            if ($type == 0) {
                $this->tpl->assign("type", $type);
                $this->tpl->assign("productlist", '');
            }
            if ($type == 1) {
                $this->tpl->assign("type", $type);
                $id = $this->input->get('id');

                $this->tpl->assign("productlist", $this->wish->displaytpl($id));
            }
            $this->tpl->display("wishproduct/creatproduct.tpl");
        }
        if ($op == "saveproduct") {
            $type = $this->input->post('type');
            $into['Parent_Unique_ID'] = $this->input->post('Parent_Unique_ID');
            $into['Unique_ID'] = $this->input->post('Unique_ID');
            $into['Product_Name'] = $this->input->post('Product_Name');
            $into['Color'] = $this->input->post('Color');
            $into['Size'] = $this->input->post('Size');
            $into['Quantity'] = $this->input->post('Quantity');
            $into['Tags'] = $this->input->post('Tags');
            $into['Description'] = $this->input->post('Description');
            $into['MSRP'] = $this->input->post('MSRP');
            $into['Price'] = $this->input->post('Price');
            $into['Shipping'] = $this->input->post('Shipping');
            $into['Product_Page'] = $this->input->post('Product_Page');
            $into['Main_Image_URL'] = $this->input->post('Main_Image_URL');
            $into['Extra_Image_URL'] = $this->input->post('Extra_Image_URL');
            $into['Shipping_Time'] = $this->input->post('Shipping_Time');
            $intojson = json_encode($into);
            if ($type == 0) {
                $this->wish->saveproduct($intojson);
            }
            if ($type == 1) {
                $id = $this->input->post('id');
                $this->wish->updata($intojson, $id);
            }
            echo "/wishproduct/wishproductupload?rand=" . mt_rand(0, 1000);
        }

        if ($op == "delect") {
            $id = $this->input->post('id');
            $this->wish->delect($id);
            echo "/wishproduct/wishproductupload?rand=" . mt_rand(0, 1000);
        }


        if ($op == "updata") {
            //从远程更新数据到本地
            $this->load->library('Amazondata');
            $this->amazondata->wishupdata();
        }

        if ($op == "status") {
            //状态显示

            $this->tpl->assign("statuslist", $this->wish->status());
            $this->tpl->display("wishproduct/status.tpl");
        }

        //获取通知，测试
        if ($op == "getmessage") {
            $this->load->library('Wishgetmessage');
            $this->wishgetmessage->getmessage();
        }


    }


}

?>